package cn.com.git.example.common.util.lock;

import cn.com.git.example.common.exception.ApiException;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * 锁的逻辑
 * @author zhangzhenfu
 * @Description
 * @date 2020/3/24 9:57
 */
public class LockContent {

    private String lockKey ;
    private boolean lockSuccess = false ;

    public LockContent() {
    }

    public LockContent(String lockKey) {
        this.lockKey = lockKey;
    }

    /**
     * 执行内容
     */
    public <T> T lock(Supplier<T> sup){
        T  result ;
        try {
            lockSuccess = LockUtil.getLock(lockKey).tryLock(LockUtil.LOCK_TIME,TimeUnit.SECONDS);
            if(lockSuccess){
                result = sup.get();
            }else {
                throw new ApiException(String.format("key %s 加锁失败 ... ",lockKey) );
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new ApiException(String.format("key %s add lock exception ... ",lockKey));
        } finally {
            //释放锁
            if(lockSuccess){
                LockUtil.getLock(lockKey).unlock();
            }
        }
        return result;
    }

}
